﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Threading;
using Brushes = System.Windows.Media.Brushes;
using Size = System.Drawing.Size;

namespace GongJu
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private bool _isWindowTopmost = false;

        private int 鼠标偏移X = 0;
        private int 鼠标偏移Y = 0;


        // 热键ID定义 - 修正了_Alt_10的值为有效的16位整数
        private const int _Alt_1 = 9001;
        private const int _Alt_2 = 9002;
        private const int _Alt_3 = 9003;
        private const int _Alt_4 = 9004;
        private const int _Alt_5 = 9005;
        private const int _Alt_6 = 9006;
        private const int _Alt_7 = 9007;
        private const int _Alt_8 = 9008;
        private const int _Alt_9 = 9009;
        private const int _Alt_10 = 9010; // 修正为有效的16位整数

        private const uint MOD_ALT = 0x0001;

        private const uint VK_0 = 0x30;             // 数字0
        private const uint VK_1 = 0x31;             // 数字1
        private const uint VK_2 = 0x32;             // 数字2
        private const uint VK_3 = 0x33;             // 数字3
        private const uint VK_4 = 0x34;             // 数字4
        private const uint VK_5 = 0x35;             // 数字5
        private const uint VK_6 = 0x36;             // 数字6
        private const uint VK_7 = 0x37;             // 数字7
        private const uint VK_8 = 0x38;             // 数字8
        private const uint VK_9 = 0x39;             // 数字9

        private System.Windows.Point _startPoint;
        private bool _isDragging = false;

        // Windows API 导入
        [DllImport("user32.dll")]
        private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);

        [DllImport("user32.dll")]
        private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

        // 导入GetClientRect API
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect);
        // 添加 WindowFromPoint API 声明
        [DllImport("user32.dll")]
        private static extern IntPtr WindowFromPoint(POINT Point);
        [DllImport("user32.dll")]
        private static extern bool ClientToScreen(IntPtr hWnd, ref POINT lpPoint);

        // 添加缺失的GetCursorPos API声明
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool GetCursorPos(out POINT lpPoint);

        // 导入GetWindowText函数
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

        // 导入GetWindowTextLength函数
        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        private static extern int GetWindowTextLength(IntPtr hWnd);

        // 定义RECT结构体
        [StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            public int Left;        // 矩形左边界的x坐标
            public int Top;         // 矩形上边界的y坐标
            public int Right;       // 矩形右边界的x坐标
            public int Bottom;      // 矩形下边界的y坐标
            public override string ToString()
            {
                return Left.ToString() + ", " + Top.ToString() + ", " + Right.ToString() + ", " + Bottom.ToString();
            }
        }

        // 添加POINT结构定义
        [StructLayout(LayoutKind.Sequential)]
        public struct POINT
        {
            public int X;
            public int Y;
        }

        private SolidColorBrush 默认笔刷;

        private SolidColorBrush 正常笔刷;

        private SolidColorBrush 按钮正常笔刷 = new SolidColorBrush(System.Windows.Media.Color.FromArgb(221, 221, 221, 221));
        private SolidColorBrush 高亮笔刷 = new SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 178, 208, 255));

        private static Window? overlayWindow;
        private static DispatcherTimer? clearTimer;
        private Window1 _crosshairWindow;
        public MainWindow()
        {
            InitializeComponent();
            捕获按钮.Content = "捕获\r按钮";
            _crosshairWindow = new Window1();

            var uiUpdateTimer = new DispatcherTimer();
            uiUpdateTimer.Interval = TimeSpan.FromMilliseconds(30); // 约30FPS更新UI
            uiUpdateTimer.Tick += UiUpdateTimer_Tick;
            uiUpdateTimer.Start();

            默认笔刷 = (SolidColorBrush)颜色.Background;
            正常笔刷 = (SolidColorBrush)坐标_1.Background;
            // 读取窗口位置
            this.Left = Properties.Settings.Default.左边;

            this.Top = Properties.Settings.Default.上边;
            this.Height = Properties.Settings.Default.高度;
            this.Width = Properties.Settings.Default.宽度;
            this.鼠标偏移.Text = Properties.Settings.Default.偏移;
            var ss = 鼠标偏移.Text.Split([',', ':', ';']);
            if (ss.Length >= 2)
            {
                鼠标偏移X = int.Parse(ss[0].Trim());
                鼠标偏移Y = int.Parse(ss[1].Trim());
            }
        }

        private void Window_SourceInitialized(object sender, EventArgs e)
        {
            // 获取窗口句柄
            IntPtr hwnd = new WindowInteropHelper(this).Handle;
            var source = HwndSource.FromHwnd(hwnd);
            source.AddHook(WndProc);
            // 注册全局热键
            var R = RegisterHotKey(hwnd, _Alt_1, MOD_ALT, VK_1);
            if (R)
                Debug.WriteLine("Alt_1 成功");
            Debug.WriteLine("Alt_1 失败");
            R = false;
            R = RegisterHotKey(hwnd, _Alt_2, MOD_ALT, VK_2);
            if (R)
                Debug.WriteLine("Alt_2 成功");
            R = false;
            R = RegisterHotKey(hwnd, _Alt_3, MOD_ALT, VK_3);
            if (R)
                Debug.WriteLine("Alt_3 成功");
            R = false;
            R = RegisterHotKey(hwnd, _Alt_4, MOD_ALT, VK_4);
            if (R)
                Debug.WriteLine("Alt_4 成功");
            R = false;
            R = RegisterHotKey(hwnd, _Alt_5, MOD_ALT, VK_5);
            if (R)
                Debug.WriteLine("Alt_5 成功");
            R = false;
            R = RegisterHotKey(hwnd, _Alt_6, MOD_ALT, VK_6);
            if (R)
                Debug.WriteLine("Alt_6 成功");
            R = false;
            R = RegisterHotKey(hwnd, _Alt_7, MOD_ALT, VK_7);
            if (R)
                Debug.WriteLine("Alt_7 成功");
            R = false;
            R = RegisterHotKey(hwnd, _Alt_8, MOD_ALT, VK_8);
            if (R)
                Debug.WriteLine("Alt_8 成功");
            R = false;
            R = RegisterHotKey(hwnd, _Alt_9, MOD_ALT, VK_9);
            if (R)
                Debug.WriteLine("Alt_9 成功");
            R = false;
            R = RegisterHotKey(hwnd, _Alt_10, MOD_ALT, VK_0); if (R)
                Debug.WriteLine("Alt_10成功");
        }

        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            const int WM_HOTKEY = 0x0312;
            switch (msg)
            {
                case WM_HOTKEY:
                    switch (wParam.ToInt32())
                    {
                        case _Alt_1:
                            执行命令(1);
                            handled = true;
                            break;
                        case _Alt_2:
                            执行命令(2);
                            handled = true;
                            break;
                        case _Alt_3:
                            执行命令(3);
                            handled = true;
                            break;
                        case _Alt_4:
                            执行命令(4);
                            handled = true;
                            break;
                        case _Alt_5:
                            执行命令(5);
                            handled = true;
                            break;
                        case _Alt_6:
                            执行命令(6);
                            handled = true;
                            break;
                        case _Alt_7:
                            执行命令(7);
                            handled = true;
                            break;
                        case _Alt_8:
                            执行命令(8);
                            handled = true;
                            break;
                        case _Alt_9:
                            执行命令(9);
                            handled = true;
                            break;
                        case _Alt_10:
                            执行命令(10);
                            handled = true;
                            break;
                    }
                    break;
            }
            return IntPtr.Zero;
        }

        public void UiUpdateTimer_Tick(object? sender, EventArgs e)
        {
            Dispatcher.BeginInvoke(() =>
            {
                GetCursorPos(out var p);
                鼠标实时X.Content = "X: " + (鼠标偏移X + p.X).ToString();
                鼠标实时Y.Content = "Y: " + (鼠标偏移Y + p.Y).ToString();
                using var bim = new Bitmap(19, 19);
                using var g = Graphics.FromImage(bim);
                g.CopyFromScreen(p.X - 9, p.Y - 9, 0, 0, new Size(19, 19));
                using var bb = NearestNeighborUpscale9(bim);
                MagnifierImage.Source = ConvertBitmapToImageSource(bb);
                if (启用辅助.IsChecked == true)
                {
                    UpdateCrosshairPosition(p);
                }
            });
        }

        private void UpdateCrosshairPosition(POINT p)
        {
            var  windowRect = GetWindowRect();
            if (windowRect.Contains(p.X, p.Y))
            {
                _crosshairWindow.Hide();
            }
            else
            {
                _crosshairWindow.UpdatePosition(p);
                _crosshairWindow.Show();
            }
        }


        private Rect GetWindowRect()
        {
            // 获取窗口在屏幕中的位置和大小
            return new Rect(
                Left,
                Top,
                ActualWidth,
                ActualHeight
            );
        }

        public Bitmap NearestNeighborUpscale9(Bitmap inputPath)
        {
            int originalWidth = inputPath.Width;
            int originalHeight = inputPath.Height;

            // 计算放大后的尺寸（宽高各放大3倍）
            int newWidth = originalWidth * 9;
            int newHeight = originalHeight * 9;

            // 创建新的 Bitmap 对象
            Bitmap newBitmap = new Bitmap(newWidth, newHeight);

            // 遍历新图像的每个像素
            for (int y = 0; y < newHeight; y++)
            {
                for (int x = 0; x < newWidth; x++)
                {
                    // 计算原图像对应的像素坐标（使用整数除法向下取整）
                    int originalX = x / 9;
                    int originalY = y / 9;

                    // 确保坐标不越界（实际上由于 x < newWidth = originalWidth*3，所以 originalX 最大为 originalWidth-1）
                    originalX = Math.Min(originalX, originalWidth - 1);
                    originalY = Math.Min(originalY, originalHeight - 1);

                    // 获取原图像对应位置的像素颜色
                    var originalColor = inputPath.GetPixel(originalX, originalY);

                    // 设置新图像的像素颜色
                    newBitmap.SetPixel(x, y, originalColor);
                }
            }
            return newBitmap;
        }

        public ImageSource ConvertBitmapToImageSource(Bitmap bitmap)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                // 将Bitmap保存到流中
                bitmap.Save(memoryStream, ImageFormat.Bmp);
                memoryStream.Position = 0;

                // 创建BitmapImage
                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.BeginInit();
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapImage.StreamSource = memoryStream;
                bitmapImage.EndInit();

                return bitmapImage;
            }
        }

        private void button10_Click(object sender, RoutedEventArgs e)
        {
            _isWindowTopmost = !_isWindowTopmost;
            this.Topmost = _isWindowTopmost;
            button10.Content = _isWindowTopmost ? "置顶" : "取消";
        }

        private void 坐标_PreviewMouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
            {
                var lable = sender as Label;
                var textToCopy = lable?.Content?.ToString();
                if (!string.IsNullOrEmpty(textToCopy))
                {
                    var labels = new Label[] { 坐标_1, 坐标_2, 坐标_3, 坐标_4, 坐标_5, 坐标_6, 坐标_7, 坐标_8, 坐标_9, 坐标_10 };
                    SetClipboardText(textToCopy);

                    foreach (var a in labels)
                    {
                        if (a != lable && a.Background != 正常笔刷)
                        {
                            a.Background = 正常笔刷;
                        }
                    }
                    lable.Background = 高亮笔刷;
                }
                e.Handled = true;
            }
        }

        public void 执行命令(int 序号)
        {
            GetCursorPos(out var p);
            Label? targetLabel = null;
            Label? targetLabel2 = null;
            Button? ctrl = null;

            // 使用字典映射序号到对应的Label，减少重复代码
            var labelMap = new Dictionary<int, Label>
            {
                {1, 坐标_1},
                {2, 坐标_2},
                {3, 坐标_3},
                {4, 坐标_4},
                {5, 坐标_5},
                {6, 坐标_6},
                {7, 坐标_7},
                {8, 坐标_8},
                {9, 坐标_9},
                {10, 坐标_10}
            };
            var labelMap2 = new Dictionary<int, Label>
            {
                {1, 颜色},
                {2, 颜色1},
                {3, 颜色2},
                {4, 颜色3},
                {5, 颜色4},
                {6, 颜色5},
                {7, 颜色6},
                {8, 颜色7},
                {9, 颜色8},
                {10, 颜色9}
            };

            var buttonlMap = new Dictionary<int, Button>
            {
                {1, Ctrl_1},
                {2, Ctrl_2},
                {3, Ctrl_3},
                {4, Ctrl_4},
                {5, Ctrl_5},
                {6, Ctrl_6},
                {7, Ctrl_7},
                {8, Ctrl_8},
                {9, Ctrl_9},
                {10, Ctrl_10}
            };


            if (labelMap.TryGetValue(序号, out targetLabel))
            {
                buttonlMap.TryGetValue(序号, out ctrl);
                内部取坐标文本(targetLabel, ctrl, p);
                labelMap2.TryGetValue(序号, out targetLabel2);
                内部设置背景色(targetLabel2, p);
            }

            void 内部取坐标文本(Label? label, Button? button, POINT pp)
            {
                if (label == null) return;
                var ss = label.Content as string;
                var X = pp.X - 鼠标偏移X;

                var Y = pp.Y - 鼠标偏移Y;
                if (string.IsNullOrEmpty(ss))
                {
                    label.Content = $"{X}, {Y}";
                    if (button != null) button.IsEnabled = false;
                    return;
                }

                var p1p2 = ss.Split(",");
                if (p1p2.Length == 2)
                {
                    // 统一处理逻辑，避免重复代码
                    label.Content = $"{p1p2[0].Trim()}, {p1p2[1].Trim()}, {X}, {Y}";
                    if (button != null) button.IsEnabled = true;
                }
                else
                {
                    label.Content = $"{X}, {Y}";
                    if (button != null) button.IsEnabled = false;
                }
            }


            void 内部设置背景色(Label? label, POINT pp)
            {
                if (label == null) return;
                label.Background = 取鼠标位置颜色(pp);
            }
        }

        [DllImport("user32.dll")]
        private static extern bool OpenClipboard(IntPtr hWndNewOwner);

        [DllImport("user32.dll")]
        private static extern bool CloseClipboard();

        [DllImport("user32.dll")]
        private static extern bool EmptyClipboard();

        [DllImport("user32.dll")]
        private static extern IntPtr SetClipboardData(uint uFormat, IntPtr hMem);

        public static bool SetClipboardText(string text)
        {
            if (!OpenClipboard(IntPtr.Zero))
                return false;

            try
            {
                EmptyClipboard();
                var buffer = System.Text.Encoding.Unicode.GetBytes(text + "\0");
                var hGlobal = Marshal.AllocHGlobal(buffer.Length);
                Marshal.Copy(buffer, 0, hGlobal, buffer.Length);
                SetClipboardData(13, hGlobal); // CF_UNICODETEXT = 13
                return true;
            }
            finally
            {
                CloseClipboard();
            }
        }

        private void 颜色_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
            {
                复制颜色(sender as Label, e);
            }
        }

        private void 复制颜色(Label? label, MouseButtonEventArgs e)
        {
            var backgroundBrush = label?.Background;
            if (backgroundBrush != null && backgroundBrush is SolidColorBrush solidBrush)
            {
                var c = solidBrush.Color;
                string colorText = $"#{c.R:X2}{c.G:X2}{c.B:X2}";
                if (!string.IsNullOrEmpty(colorText))
                {
                    SetClipboardText(colorText);
                }
                e.Handled = true;
            }
        }

        private void Ctrl_1_Click(object sender, RoutedEventArgs e)
        {
            // 使用发件人对象的Tag属性来确定对应的Label，减少重复代码
            if (sender is Button button && button.Tag is string tag)
            {
                if (int.TryParse(tag, out int index) && index >= 1 && index <= 10)
                {
                    Label? targetLabel = null;

                    switch (index)
                    {
                        case 1: targetLabel = 坐标_1; break;
                        case 2: targetLabel = 坐标_2; break;
                        case 3: targetLabel = 坐标_3; break;
                        case 4: targetLabel = 坐标_4; break;
                        case 5: targetLabel = 坐标_5; break;
                        case 6: targetLabel = 坐标_6; break;
                        case 7: targetLabel = 坐标_7; break;
                        case 8: targetLabel = 坐标_8; break;
                        case 9: targetLabel = 坐标_9; break;
                        case 10: targetLabel = 坐标_10; break;
                    }

                    if (targetLabel != null)
                    {
                        截图(targetLabel);
                        button.Background = 高亮笔刷;
                    }
                }
            }
        }

        private void 截图(Label label)
        {
            var ss = label.Content as string;
            if (!string.IsNullOrEmpty(ss))
            {
                var p1p2 = ss.Split(",");
                if (p1p2.Length == 4)
                {
                    try
                    {
                        var x = int.Parse(p1p2[0].Trim()) + 鼠标偏移X;
                        var y = int.Parse(p1p2[1].Trim()) + 鼠标偏移Y;
                        var x2 = int.Parse(p1p2[2].Trim()) + 鼠标偏移X;
                        var y2 = int.Parse(p1p2[3].Trim()) + 鼠标偏移Y;

                        // 确保坐标正确（防止负尺寸）
                        int width = Math.Abs(x2 - x);
                        int height = Math.Abs(y2 - y);
                        int left = Math.Min(x, x2);
                        int top = Math.Min(y, y2);

                        using var bim = new Bitmap(width, height);
                        using var g = Graphics.FromImage(bim);
                        g.CopyFromScreen(left, top, 0, 0, bim.Size);

                        // 确保保存目录存在
                        string screenshotsDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "截图");
                        if (!Directory.Exists(screenshotsDir))
                        {
                            Directory.CreateDirectory(screenshotsDir);
                        }

                        var 名称 = ss.Replace(',', '_');
                        var 路径 = Path.Combine(screenshotsDir, 名称 + ".bmp");
                        bim.Save(路径, ImageFormat.Bmp);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"截图保存失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
        }

        public SolidColorBrush 取鼠标位置颜色(POINT p)
        {
            using var bim = new Bitmap(1, 1);
            using var g = Graphics.FromImage(bim);
            g.CopyFromScreen(p.X, p.Y, 0, 0, bim.Size);
            var color = bim.GetPixel(0, 0);
            return new SolidColorBrush(System.Windows.Media.Color.FromArgb(color.A, color.R, color.G, color.B));
        }

        private void button10复制__C__Click(object sender, RoutedEventArgs e)
        {
            // 清空所有坐标标签
            坐标_1.Content = "";
            坐标_2.Content = "";
            坐标_3.Content = "";
            坐标_4.Content = "";
            坐标_5.Content = "";
            坐标_6.Content = "";
            坐标_7.Content = "";
            坐标_8.Content = "";
            坐标_9.Content = "";
            坐标_10.Content = "";

            坐标_1.Background = 正常笔刷;
            坐标_2.Background = 正常笔刷;
            坐标_3.Background = 正常笔刷;
            坐标_4.Background = 正常笔刷;
            坐标_5.Background = 正常笔刷;
            坐标_6.Background = 正常笔刷;
            坐标_7.Background = 正常笔刷;
            坐标_8.Background = 正常笔刷;
            坐标_9.Background = 正常笔刷;
            坐标_10.Background = 正常笔刷;

            颜色.Background = 默认笔刷;
            颜色1.Background = 默认笔刷;
            颜色2.Background = 默认笔刷;
            颜色3.Background = 默认笔刷;
            颜色4.Background = 默认笔刷;
            颜色5.Background = 默认笔刷;
            颜色6.Background = 默认笔刷;
            颜色7.Background = 默认笔刷;
            颜色8.Background = 默认笔刷;
            颜色9.Background = 默认笔刷;

            Ctrl_1.IsEnabled = false;
            Ctrl_2.IsEnabled = false;
            Ctrl_3.IsEnabled = false;
            Ctrl_4.IsEnabled = false;
            Ctrl_5.IsEnabled = false;
            Ctrl_6.IsEnabled = false;
            Ctrl_7.IsEnabled = false;
            Ctrl_8.IsEnabled = false;
            Ctrl_9.IsEnabled = false;
            Ctrl_10.IsEnabled = false;
        }

        private void 鼠标偏移_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Return)
            {
                try
                {
                    var ss = 鼠标偏移.Text.Split([',', ':', ';']);
                    if (ss.Length >= 2)
                    {
                        鼠标偏移X = int.Parse(ss[0].Trim());
                        鼠标偏移Y = int.Parse(ss[1].Trim());
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"无效的偏移值: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        // 窗口关闭时释放资源
        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            _crosshairWindow.Close();
            Cursor = Cursors.Arrow;

            // 注销热键
            IntPtr hwnd = new WindowInteropHelper(this).Handle;
            UnregisterHotKey(hwnd, _Alt_1);
            UnregisterHotKey(hwnd, _Alt_2);
            UnregisterHotKey(hwnd, _Alt_3);
            UnregisterHotKey(hwnd, _Alt_4);
            UnregisterHotKey(hwnd, _Alt_5);
            UnregisterHotKey(hwnd, _Alt_6);
            UnregisterHotKey(hwnd, _Alt_7);
            UnregisterHotKey(hwnd, _Alt_8);
            UnregisterHotKey(hwnd, _Alt_9);
            UnregisterHotKey(hwnd, _Alt_10);
            // 读取窗口位置
            Properties.Settings.Default.左边 = this.Left;
            Properties.Settings.Default.上边 = this.Top;
            Properties.Settings.Default.高度 = this.Height;
            Properties.Settings.Default.宽度 = this.Width;
            Properties.Settings.Default.偏移 = this.鼠标偏移.Text;
            Properties.Settings.Default.Save();
        }


        private void 捕获_MouseMove(object sender, MouseEventArgs e)
        {
            捕获_鼠标移动(捕获按钮, e);
        }

        private void 捕获_鼠标移动(Button 按钮, MouseEventArgs e)
        {
            if (_isDragging)
            {
                System.Windows.Point currentPosition = e.GetPosition(this);
                double offsetX = currentPosition.X - _startPoint.X;
                double offsetY = currentPosition.Y - _startPoint.Y;
                Canvas.SetLeft(按钮, Canvas.GetLeft(按钮) + offsetX);
                Canvas.SetTop(按钮, Canvas.GetTop(按钮) + offsetY);
                _startPoint = currentPosition;
            }
        }

        private void 捕获_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            捕获_鼠标按下(捕获按钮, e);
        }

        private void 捕获_鼠标按下(Button 按钮, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                _startPoint = e.GetPosition(this);
                _isDragging = true;
                this.Cursor = Cursors.Hand;
                按钮.CaptureMouse();
            }
        }

        private void 捕获_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            捕获_鼠标松开(捕获按钮);
        }

        private void 捕获_鼠标松开(Button 按钮)
        {
            if (_isDragging)
            {
                _isDragging = false;
                按钮.ReleaseMouseCapture();
                // 获取鼠标当前屏幕坐标
                System.Windows.Point screenPoint = Mouse.GetPosition(null);
                System.Windows.Point winformsPoint = 按钮.PointToScreen(screenPoint);
                var 窗口句柄 = WindowFromPoint(new POINT { X = (int)winformsPoint.X, Y = (int)winformsPoint.Y });
                var 标题 = GetWindowTitle(窗口句柄);
                this.Title = 标题 != null ? 标题 + " " + 窗口句柄.ToString() : "捕获窗口: " + 窗口句柄.ToString();
                HighlightWindowClientArea(窗口句柄);
            }
            this.Cursor = Cursors.Arrow;
        }

        public static string GetWindowTitle(IntPtr windowHandle)
        {
            // 先获取标题长度
            int length = GetWindowTextLength(windowHandle);
            if (length <= 0)
                return string.Empty; // 没有标题或窗口句柄无效

            // 创建足够大的StringBuilder来存储标题
            StringBuilder title = new StringBuilder(length + 1);

            // 获取窗口标题
            if (GetWindowText(windowHandle, title, title.Capacity) > 0)
                return title.ToString();
            else
                return string.Empty; // 获取失败
        }

        public void HighlightWindowClientArea(IntPtr windowHandle, int durationSeconds = 3)
        {
            if (!GetClientRect(windowHandle, out RECT clientRect))
                return;

            // 转换为屏幕坐标
            POINT topLeft = new POINT { X = clientRect.Left, Y = clientRect.Top };
            POINT bottomRight = new POINT { X = clientRect.Right, Y = clientRect.Bottom };
            ClientToScreen(windowHandle, ref topLeft);
            ClientToScreen(windowHandle, ref bottomRight);

            鼠标偏移.Text = $"{topLeft.X} : {topLeft.Y}";
            鼠标偏移X = topLeft.X;
            鼠标偏移Y = topLeft.Y;
            // 创建UI元素
            Application.Current.Dispatcher.Invoke(() =>
            {
                // 创建无边框透明窗口
                overlayWindow = new Window
                {
                    WindowStyle = WindowStyle.None,
                    AllowsTransparency = true,
                    Background = Brushes.Transparent,
                    Topmost = true,
                    ShowInTaskbar = false,
                    Width = bottomRight.X - topLeft.X,
                    Height = bottomRight.Y - topLeft.Y,
                    Left = topLeft.X,
                    Top = topLeft.Y,
                    WindowState = WindowState.Normal
                };

                // 创建矩形边框
                var rectangle = new System.Windows.Shapes.Rectangle
                {
                    Width = overlayWindow.Width,
                    Height = overlayWindow.Height,
                    Stroke = Brushes.Green,
                    StrokeThickness = 4,
                    Fill = Brushes.Transparent
                };

                // 禁用窗口交互
                rectangle.IsHitTestVisible = false;

                // 添加到画布
                var canvas = new Canvas();
                canvas.Children.Add(rectangle);
                overlayWindow.Content = canvas;

                // 显示窗口
                overlayWindow.Show();

                // 设置定时器自动关闭
                clearTimer = new DispatcherTimer
                {
                    Interval = TimeSpan.FromSeconds(durationSeconds)
                };
                clearTimer.Tick += (sender, e) =>
                {
                    clearTimer.Stop();
                    overlayWindow?.Close();
                };
                clearTimer.Start();
            });
        }

        private void checkBox_Checked(object sender, RoutedEventArgs e)
        {
            // 显示十字线窗口
            _crosshairWindow.Show();
        }

        private void 启用辅助_Unchecked(object sender, RoutedEventArgs e)
        {
            // 隐藏十字线窗口
            _crosshairWindow.Hide();

        }

        private void button_Click(object sender, RoutedEventArgs e)
        {
            try
            {

                // 确保保存目录存在
                string screenshotsDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "截图");
                if (!Directory.Exists(screenshotsDir))
                {
                    Directory.CreateDirectory(screenshotsDir);
                }
                // 使用Process.Start打开资源管理器并定位到指定目录
                Process.Start("explorer.exe", $"\"{screenshotsDir}\"");
            }
            catch
            {
                return;
            }

        }
    }
}